package com.zhenwei.zscm.common.utils;

import cn.hutool.jwt.JWT;

import java.nio.charset.StandardCharsets;

public class JwtHandler {
    private static final long JWT_EXPIRE_TIME = 24 * 60 * 60 * 1000;

    private static final String JWT_SECRET = "zhenwei";
    /**
     * 生成一个加密的jwt
     * @param userId 用户id
     * @return jwt
     */
    public static String generateJwt(String userId){
        return JWT.create()
                .setPayload("userId", userId)
                .setPayload("expiredTime", System.currentTimeMillis() + JWT_EXPIRE_TIME)
                .setKey(JWT_SECRET.getBytes(StandardCharsets.UTF_8))
                .sign();
    }

    /**
     * 检查jwt是否合法或过期
     * @param jwt jwt
     * @return 合法返回用户Id，不合法返回空
     */
    public static String validJwt(String jwt) {
        try {
            boolean valid = JWT.of(jwt).setKey(JWT_SECRET.getBytes(StandardCharsets.UTF_8)).verify();
            if(!valid) {
                return "";
            }
            var userId = JWT.of(jwt).getPayload("userId").toString();
            var expiredTime = Long.parseLong(JWT.of(jwt).getPayload("expiredTime").toString());
            if(expiredTime > System.currentTimeMillis()){
                return userId;
            }
            // 返回token无效的错误信息
            System.out.println("token->"+jwt);
            System.out.println("userId->"+userId);
            System.out.println("expiredTime->"+expiredTime);
            return "";
        } catch (Exception e) {
            return "";
        }
    }
}
